package com.genITeam.ria.bl;

import java.util.ArrayList;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.genITeam.ria.constant.Constants;
import com.genITeam.ria.dao.HomeDAO;
import com.genITeam.ria.exception.NGFException;
import com.genITeam.ria.utility.HibernateUtils;
import com.genITeam.ria.utility.Utility;
import com.genITeam.ria.vo.Buddy;
import com.genITeam.ria.vo.FavouriteForum;
import com.genITeam.ria.vo.Member;
import com.genITeam.ria.vo.ResponseVo;
import com.genITeam.ria.vo.Posts;

/**
 * @author Administrator
 * 
 */
public class HomeBL {

	public HomeBL() {
		BasicConfigurator.configure();
	}

	Logger logger = Logger.getLogger(HomeBL.class);


	/**
	 * generateBuddiesData Generate the Buddies data and return in XML format
	 * 
	 * @param memberId
	 * 
	 * @return String
	 * @throws NGFException
	 */

	public String generateBuddiesData(String memberId) throws NGFException {
		String xmlBuddiesData = "";
		Session session = null;
		Transaction tx = null;
		try {
			logger.info("Start generateBuddiesData");
			HomeDAO homeDAO = new HomeDAO();
			session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			ResponseVo responseVo = homeDAO.getBuddiesData(Integer
					.parseInt(memberId), session);
			ArrayList buddy = responseVo.getBuddy();

			if( buddy.size()>0){
				xmlBuddiesData = this.generateBuddiesxml(buddy);
			}else{
				xmlBuddiesData = "<message>No Buddies Added</message>";
			}
			tx.commit();

		} catch (Exception e) {
			System.out.println(e.toString());
			if (tx != null && tx.isActive()) {
				tx.rollback();
			} // end of if
			logger.error("Exception = "+e.toString());
			throw new NGFException(e.getMessage());

		}

		return xmlBuddiesData;
	}

	/**
	 * generateBuddiesxml Generate the Buddies XML and return to caller fuction
	 * 
	 * @param ArrayList
	 * 
	 * @return String
	 * @throws NGFException
	 */

	public String generateBuddiesxml(ArrayList buddyList) throws NGFException {
		StringBuffer xml = new StringBuffer("");
		Buddy buddy = null;
		Member member = null;
		try {
			logger.info("Start generateBuddiesxml");
			xml = new StringBuffer("<contact>\n");
			for (int i = 0; i < buddyList.size(); i++) {
				buddy = (Buddy) buddyList.get(i);
				member = (Member) buddy.getMember();
				xml.append("<item>");
				xml.append("<id>" + member.getId() + "</id>");
				xml.append("<firstName>" + Utility.getStringValue(member.getFirstName(),"")
						+ "</firstName>");
				xml.append("<lastName>" + Utility.getStringValue(member.getLastName(),"") + "</lastName>");
				xml.append("<nick>" + Utility.getStringValue(member.getNick(),"") + "</nick>");
				xml.append("<email>" + Utility.getStringValue(member.getEmail(),"") + "</email>");
				xml.append("<phone>" + Utility.getStringValue(member.getPhone(),"") + "</phone>");
				xml.append("<address>" + Utility.getStringValue(member.getAddress(),"") + "</address>");
				xml.append("<joinedOn>" + member.getJoinedOn() + "</joinedOn>");
				xml.append("<userName>" + Utility.getStringValue(member.getUserName(),"") + "</userName>");
				xml.append("</item>");
				xml.append("\n");

			}// end for

			xml.append("</contact>");

			System.out.println(xml);
			logger.info("xml = " + xml.toString());
		} catch (Exception e) {
			logger.error("Exception = "+e.toString());
			System.out.println(e.toString());
			throw new NGFException(e.getMessage());

		}

		return xml.toString();
	}

	/**
	 * generateFavouriteForumData Generate the Favourite Forum XML
	 * 
	 * @param String
	 * 
	 * @return String
	 * @throws NGFException
	 */

	public String generateFavouriteForumData(String memberId)
			throws NGFException {
		String xmlFavouriteForum = "";
		Session session = null;
		Transaction tx = null;
		try {
			logger.info("Start generateFavouriteForumData");
			HomeDAO homeDAO = new HomeDAO();
			session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			ResponseVo responseVo = homeDAO.getFavouriteForumData(Integer
					.parseInt(memberId), session);
			ArrayList favouriteForum = responseVo.getFavouriteForum();
			if( favouriteForum.size() > 0 ){
				xmlFavouriteForum = this.generateForumMemberxml(favouriteForum);
			}else{
				xmlFavouriteForum = "<message>No Record Found</message>";
			}
			tx.commit();
		} catch (Exception e) {
			if (tx != null && tx.isActive()) {
				tx.rollback();
			} // end of if
			logger.error("Exception = "+e.toString());
			throw new NGFException(e.getMessage());
		}

		return xmlFavouriteForum;
	}

	/**
	 * generateForumMemberxml Generate the Favourite Forum XML and return to
	 * caller function
	 * 
	 * @param ArrayList         
	 * 
	 * @return String
	 * @throws NGFException
	 */

	public String generateForumMemberxml(ArrayList favouriteForumDetail)
			throws NGFException {
		FavouriteForum favouriteForum = null;
		StringBuffer xml = new StringBuffer("");
		try {
			logger.info("Start generateForumMemberxml");

			int size = favouriteForumDetail.size();
			xml = new StringBuffer("<resultset>\n");
			
			int maxRecord = Constants.HOME_FAVOURITE_FORUM_RECORD;
			if(size > maxRecord){
				size = maxRecord;
			}
			
			for (int i = 0; i < size; i++) {

				favouriteForum = (FavouriteForum) favouriteForumDetail.get(i);

				xml.append("<w threadtitle=\""
						+ Utility.getStringValue(favouriteForum.getPosts().getTitle(),"") + "\" ");
				xml.append(" noofviews=\""
						+ favouriteForum.getPosts().getNoOfView() + "\" ");
				xml.append(" writtenby=\""
						+ Utility.getStringValue(favouriteForum.getPosts().getMember().getNick(),"")
						+ "\" ");
				xml.append(" posted=\""
						+ favouriteForum.getPosts().getPostDate() + "\"");
				xml.append(" postId=\"" + favouriteForum.getPosts().getPostId()
						+ "\"");
				xml.append(" />");
				xml.append("\n");

			}// end for

			xml.append("</resultset>");
			System.out.println(xml.toString());
			logger.info("xml = " + xml.toString());
		} catch (Exception e) {
			logger.error("Exception = "+e.toString());
			throw new NGFException(e.getMessage());
		}

		return xml.toString();
	}

	/**
	 * generateMemberThreadData Generate the Member Thread XML
	 * 
	 * @param String
	 *            	 
	 * @return String
	 * @throws NGFException
	 */

	public String generateMemberThreadData(String memberId) throws NGFException {
		String xmlMemberThread = "";
		Session session = null;
		Transaction tx = null;
		try {
			logger.info("Start generateMemberThreadData");
			HomeDAO homeDAO = new HomeDAO();
			session = HibernateUtils.getSessionFactory().getCurrentSession();
			tx = session.getTransaction();
			tx.begin();
			ResponseVo responseVo = homeDAO.getMemberThreadData(Integer
					.parseInt(memberId), session);
			ArrayList memberThread = responseVo.getMemberThread();
			if( memberThread.size() > 0){
				xmlMemberThread = this.generateMyPostxml(memberThread);
			}else{
				xmlMemberThread = "<message>You have Posted No Post</message>";
			}
			tx.commit();
		} catch (Exception e) {
			if (tx != null && tx.isActive()) {
				tx.rollback();
			} // end of if
			logger.error("Exception = "+e.toString());
			throw new NGFException(e.getMessage());

		}

		return xmlMemberThread;
	}

	/**
	 * generateMyPostxml Generate the Member Thread XML and return to caller function
	 * 
	 * @param String       
	 * 
	 * @return String
	 * @throws NGFException
	 */

	public String generateMyPostxml(ArrayList myPostDetail) throws NGFException {
		Posts posts = null;
		StringBuffer xml = new StringBuffer("");
		try {
			logger.info("Start generateMyPostxml");
			int size = myPostDetail.size()-1;
//			if (size > 10) {
//				size = 10;
//			}
			xml = new StringBuffer("<resultset>\n");

			int maxRecord = Constants.HOME_MY_POST_RECORD;
			
			for (int i = 0, j = 0; i < size && j<=maxRecord ;i++) {

				posts = (Posts) myPostDetail.get(i);

				if (posts.getPostType() == 'P') {
					j++;
					xml.append("<w threadtitle=\"" + Utility.getStringValue(posts.getTitle(),"") + "\" ");
					xml.append(" noofviews=\"" + posts.getNoOfView() + "\" ");
					xml.append(" writtenby=\"" + Utility.getStringValue(posts.getMember().getNick(),"")
							+ "\" ");
					xml.append(" posted=\"" + posts.getPostDate() + "\"");
					xml.append(" noofreplay=\"" + posts.getNoOfView() + "\"");
					xml.append(" parentId=\"" + posts.getPosts().getPostId()
							+ "\"");
					xml.append(" postId=\"" + posts.getPostId() + "\"");
					xml.append(" />");
					xml.append("");
				}

			}// end for
			xml.append("</resultset>");
			System.out.println(xml.toString());
			logger.info("xml = " + xml.toString());
		} catch (Exception e) {
			logger.error("Exception = "+e.toString());
			System.out.println(e.toString());
			throw new NGFException(e.getMessage());

		}

		return xml.toString();
	}


	public static void main(String a[]) throws NGFException {
		HomeBL homeBL = new HomeBL();
		try {

			// homeBL.generateBuddiesData("1");
			// homeBL.generateFavouriteMemberData();
			// homeBL.generateFavouriteForumData("1");
			homeBL.generateMemberThreadData("1");

		} catch (Exception e) {
			throw new NGFException(e.getMessage());

		}

	}	
}
